<template>
    <div class="user-set-container">
        <TridentNavBar>
            <template #left><i class="icon iconfont icon-zuojiantou"></i></template>
            <template #default>个人设置</template>
        </TridentNavBar>

        <div class="user-set-box">
			<!-- 头像 -->
			<div class="avatar-box">
				<div class="avatar-item">
					<div>
						<van-uploader
							:after-read="afterRead"
						>
							<van-image class="image" v-if="userStore.profile && userStore.profile.user.avatar_url" 
								round
								width="50"
								height="50"
								:src="global.MINIO_FILE_DOMAIN + userStore.profile?.user?.avatar_url"
							/>
							<van-image v-else
								round
								width="50"
								height="50"
								:src="avatarImage"
							/>

						</van-uploader>
					</div>
					<div class="avatar-text">点击修改</div>
				</div>

				<div class="username-item">
					<div class="username">{{ userStore.profile?.user?.username }}</div>
					<div
						v-if="userStore.profile && userStore.profile.user.avatar_url"
						class="preview-avatar" 
						@click="previewAvatar(global.MINIO_FILE_DOMAIN + userStore.profile?.user?.avatar_url)"
					>预览头像</div>
				</div>
			</div>

            <!-- 昵称 -->
            <van-cell
                title="昵称"
				size="large"
                is-link
                to="/editNick"
                :value="userStore.profile?.user?.nick ? userStore.profile?.user?.nick : '未设置'"
            />

            <!-- 手机号 -->
            <van-cell
                title="手机号"
				size="large"
                is-link
                to="/editMobile"
                :value="userStore.profile?.user?.mobile"
            />

            <!-- 邮箱 -->
            <van-cell
                title="邮箱"
				size="large"
                is-link
                to="/editEmail"
                :value="userStore.profile?.user?.email"
            />

			<!-- 地区 -->
            <van-cell
                title="地区"
				size="large"
                is-link
                to="/editRegion"
                :value="userStore.profile?.user?.region"
            />

            <!-- 其他信息 -->
            <van-cell
                title="其他信息"
				size="large"
                is-link
				to="/otherInfo"
            />

            <!-- 修改密码 -->
            <van-cell
                title="修改密码"
				size="large"
                is-link
                to="/changePassword"
            />
		</div>
		
		<!-- 版本 -->
        <div class="version">
            <van-cell
                title="版本"
				size="large"
                value="1.0.0"
            />
        </div>
		
		<!-- 退出按钮 -->
		<div class="logout-btn">
			<van-button color="red" block type="primary" @click="handleLogout">退出登录</van-button>
		</div>

		<!-- 图片裁剪弹层 -->
		<van-popup v-model:show="showCropper" @click-overlay="cancelCropperAvatar">
			<div class="button-group">
				<van-button style="width: 50px;height: 30px;" color="#27BA9B" type="success" size="mini" @click="handleConfirmCropperAvatar">确定</van-button>
				<van-button type="primary" size="mini" @click="handleRotateLeft">向左旋转</van-button>
				<van-button type="primary" size="mini" @click="handleRotateRight">向右旋转</van-button>
				<van-button style="width: 50px;height: 30px;" type="danger" size="mini" @click="cancelCropperAvatar">取消</van-button>
			</div>
			<VueCropper
				ref="cropper"
				:img="option.img"
				:outputSize="option.outputSize"
				:outputType="option.outputType"
				:info="option.info"
				:full="option.full"
				:autoCropWidth="option.autoCropWidth"
				:autoCropHeight="option.autoCropHeight"
				:canMove="option.canMove"
				:canMoveBox="option.canMoveBox"
				:original="option.original"
				:autoCrop="option.autoCrop"
				:fixed="option.fixed"
				:fixedNumber="option.fixedNumber"
				:centerBox="option.centerBox"
				:infoTrue="option.infoTrue"
				:fixedBox="option.fixedBox"
				:high="option.high"
				:mode="option.mode"
			/>
		</van-popup>
    </div>
</template>

<script setup lang="ts">
import { inject, ref } from "vue"
import { showConfirmDialog, showSuccessToast, showImagePreview, showToast } from 'vant'
import {useRouter} from 'vue-router'
import { reqUploadImageAPI } from '@/apis/uploadFile'

// 导入图片裁剪插件
import 'vue-cropper/dist/index.css'
import { VueCropper }  from "vue-cropper"

// 导入存储
import { useUserStore } from '@/store/modules/user'
import avatarImage from '@/assets/images/avatar.png'
import { socket } from "@/utils/socketIO"

// 全局属性
const global: any = inject('global')

// 用户存储
const userStore = useUserStore()

// 路由器
const router = useRouter()



// --------------- 退出登录功能开始 ---------------
const handleLogout = () => {
	showConfirmDialog({
		title:'提示',
		message:'确定要退出吗?',
		confirmButtonColor: '#27BA9B'
	}).then(()=>{
		// 清空用户信息
		userStore.clearProfile()

		// 清空收货地址信息
		userStore.clearDeliveryAddr()

		// 关闭socket.io连接
		socket.value.close()

		showSuccessToast('退出成功')
		setTimeout(() => {
			// 跳转登录页面
			router.push({path: '/passwordLogin'})
		}, 1500)
	}).catch(() => {})
}
// --------------- 退出登录功能结束 ---------------



// ------------ 头像裁剪、上传功能开始 ------------
// 裁剪组件
const cropper = ref()

// 裁剪参数
const option: any = ref({
	img: null, 			// 裁剪图片的地址
	outputSize: 1, 		//裁剪生成图片的质量(可选0.1 - 1)
	info: true, 		// 图片大小信息
	outputType: 'jpeg', // 裁剪生成图片的格式（jpeg || png || webp）
	canScale: false, 	// 图片是否允许滚轮缩放
	autoCrop: true, 	// 是否默认生成截图框
	autoCropWidth:  '100px', // 默认生成截图框宽度
	autoCropHeight: '100px', // 默认生成截图框高度
	high: true, // 是否按照设备的dpr 输出等比例图片
	fixedBox: false, // 固定截图框大小 不允许改变
	fixed: true, // 是否开启截图框宽高固定比例
	fixedNumber: [1, 1], // 截图框的宽高比例
	full: true, // 是否输出原图比例的截图
	canMoveBox: true, // 截图框能否拖动
	original: false, // 上传图片按照原始比例渲染
	centerBox: true, // 截图框是否被限制在图片里面
	infoTrue: false, // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
	mode: '100% auto' // 图片默认渲染方式
})

// 弹层
const showCropper = ref(false)

// 选取图片后
const afterRead = async (file: any) => {
	// 图片类型限制
	const imageTypes = [
		'image/jpg',
		'image/jpeg',
		'image/png',
	]
	if (!imageTypes.includes(file.file.type)) {
		showToast('图片类型要求：jpeg、jpg、png')
		return false
	}

	// 图片大小限制 2M
	if (file.file.size > 1024 * 1024 * 2) {
		showToast('图片大小不能超过2M')
		return false
	}
	option.value.img = file.objectUrl
	showCropper.value = true
}

/**
 * 取消裁剪
 */
const cancelCropperAvatar = () => {
  showCropper.value = false
}

/**
 * 处理确认裁剪头像
 */
const handleConfirmCropperAvatar = () => {
	// 获取截图的blob数据
	cropper.value.getCropBlob(async (data: any)=>{
		const formData = new FormData()
		formData.append("image", data, 'xxx.jpg') // 必须要第三个参数，名称随便
		const {data:result} = await reqUploadImageAPI(formData)
		if (result.status_code != 200) {
			showToast(result.message)
			return false
		}

		// 更新头像
		await userStore.modifyAvatar({avatar_url: result.data.relative_url})
		showSuccessToast('修改成功')
		setTimeout(() => {
		    router.push({path: '/me'})
		}, 1000)

		showCropper.value = false
	})
}
// ------------ 头像裁剪、上传功能结束 ------------



// ------------- 向左、右旋转功能开始 -------------
const handleRotateLeft = () => {
	cropper.value.rotateLeft()
}

const handleRotateRight = () => {
	cropper.value.rotateRight()
}
// ------------- 向左、右旋转功能结束 -------------



// --------------- 预览头像功能开始 ---------------
const previewAvatar = (avatar: string) => {
	showImagePreview ([avatar])
}
// --------------- 预览头像功能结束 ---------------
</script>

<style scoped lang="scss">
:deep(.van-popup) {
  width: 80%;
  height: 80%;
  overflow: hidden;
}
.button-group {
  display: flex;
  justify-content: space-between;
  button {
    margin: 10px;
  }
}
.user-set-container {
    height: calc(100vh - 45px);
    background-color: ghostwhite;
	margin-top: 45px;
}
.logout-btn {
    padding: 10px;
}

.avatar-box {
	display: flex;
	align-items: center;
	// justify-content: space-between;
	background-color: white;
	padding: 15px;
	.avatar-item {
		// margin: 5px;
		.avatar-text {
			font-size: 12px;
			color: gray;
		}
		.image {
			border: 1px solid gainsboro;
			border-radius: 50%;
			padding: 3px;
		}
	}
	.username-item {
		display: flex;
		align-items: center;
		.username {
			font-size: 14px;
			margin-left: 10px;
			font-weight: bold;
			width: 190px;


			overflow: hidden;
			white-space: nowrap;
			text-overflow: ellipsis;
		}
		.preview-avatar {
			position: absolute;
			right: 0;
			margin-right: 17px;
			font-size: 14px;
			color: gray;
			&::after {
				position: sticky;
				top: 50%;
				padding-left: 7px;
				content: '\e607';
				color: #BBBBBB;
				font-family: 'iconfont' !important;
				font-size: 15px;
				transform: translateY(-50%);
			}
		}
	}
}
</style>